import React, { useContext, useState } from 'react'
import './index.css'

import { AppContext } from '../../../App'

export default function Item({ todo, done, id }) {

  // 发布组件上下文(content)
  const {todoList, setTodoList} = useContext(AppContext)

  const [active, setActive] = useState(false)

  // 鼠标移入函数柯里化
  const mouseMoveHandler = (moveStatus) => {
    return () => {
      setActive(moveStatus)
    }
  }

  // 多选框
  const checkChangeHandler = (e) => {
    const newTodoList = todoList.map(item => {
      if (item.id === id) {
        return { ...item, done: e.target.checked }  // 最好不要影响之前的数据
      }
      return item
    })
    setTodoList(newTodoList)
  }

  // 删除
  const deleteTodoHandler = () => {
    console.log(1);
    const newTodoList = todoList.filter(item => {
      return item.id === id ? false : true
    })
    setTodoList(newTodoList)
  }

  return (
    <li
      /* 
        onMouseEnter 是 react 提供，相比原生，会有冒泡
      */
      onMouseEnter={mouseMoveHandler(true)}
      onMouseLeave={mouseMoveHandler(false)}
      className={active ? 'active' : ''}
    >
      <label>
        <input type="checkbox" checked={done} onChange={checkChangeHandler} />
        <span>{todo}</span>
      </label>
      <button className="btn btn-danger" onClick={deleteTodoHandler} style={{ display: active ? 'block' : 'none' }}>删除</button>
    </li>
  )
}
